<template>
  <div class="connection-status">
    <el-tooltip :content="statusText" placement="top">
      <div :class="['status-dot', connectionStatus]"></div>
    </el-tooltip>
    <span class="status-label">{{ statusLabel }}</span>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { voiceWebSocket } from '@/services/websocket'

// 响应式数据
const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected')
const lastHeartbeat = ref(0)

// 计算属性
const statusText = computed(() => {
  switch (connectionStatus.value) {
    case 'connected':
      const timeSinceHeartbeat = Date.now() - lastHeartbeat.value
      return `已连接 - 最后心跳: ${Math.floor(timeSinceHeartbeat / 1000)}秒前`
    case 'connecting':
      return '连接中...'
    case 'disconnected':
      return '连接已断开'
    default:
      return '未知状态'
  }
})

const statusLabel = computed(() => {
  switch (connectionStatus.value) {
    case 'connected':
      return '已连接'
    case 'connecting':
      return '连接中'
    case 'disconnected':
      return '已断开'
    default:
      return '未知'
  }
})

// 监控定时器
let statusCheckInterval: number | null = null

// 检查连接状态
const checkConnectionStatus = () => {
  if (voiceWebSocket.isConnected) {
    connectionStatus.value = 'connected'
    lastHeartbeat.value = voiceWebSocket.lastHeartbeat
  } else {
    connectionStatus.value = 'disconnected'
  }
}

// 组件挂载
onMounted(() => {
  checkConnectionStatus()
  
  // 每5秒检查一次连接状态
  statusCheckInterval = window.setInterval(() => {
    checkConnectionStatus()
  }, 5000)
})

// 组件卸载
onUnmounted(() => {
  if (statusCheckInterval) {
    clearInterval(statusCheckInterval)
  }
})
</script>

<style scoped>
.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.status-dot.connected {
  background: #67c23a;
  box-shadow: 0 0 8px rgba(103, 194, 58, 0.5);
}

.status-dot.connecting {
  background: #e6a23c;
  animation: pulse 1.5s infinite;
}

.status-dot.disconnected {
  background: #f56c6c;
}

.status-label {
  color: #606266;
  font-weight: 500;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}
</style>
